var amapFile = require('../../../libs/amap-wx.js');
var util = require('../../../libs/util.js');
var amap, mapCtx;
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: '',
    humidity: 0,
    latitude: 0,//纬度 
    longitude: 0,//经度 
    speed: 0,//速度 
    accuracy: 16,//位置精准度 
    navLat: 0,//导航纬度 
    navLon: 0,//导航经度 
    markers: [],
    polyline: [],
    "include-points": [],
    vehicleType: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    var that = this;
    wx.setNavigationBarTitle({ "title": "路线规划设置--" + app.appName });
    if(e.id){
      that.setData({
        id: e.id
      });
    }
    if (e.name) {
      that.setData({
        name: e.name
      });
    }
    if (e.coord) {
      that.setData({
        wh_coord: e.coord
      });
    }
    if (e.strategy) {
      that.setData({
        strategy: e.strategy
      });
    }
    if (e.routing_type) {
      that.setData({
        vehicleType: e.routing_type == 'truck' ? false : true
      });
    }
    //手机定位
    that.getLocation();
    //获取路线策略
    that.getData();
    //地图初始化
    that.initMap();
  },
  getLocation() {
    var that = this;
    //获取手机定位坐标
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        //console.log(res)
        var latitude = res.latitude;
        var longitude = res.longitude;
        that.setData({
          longitude: longitude,
          latitude: latitude
        });
      }
    });
  },
  getData: function () {
    wx.showLoading({
      title: '加载数据中...'
    });
    var that = this;
    util.getData("/xypapi/map/routerCalculate/routerStrategy", {
      vehicle_type: that.data.vehicleType?'driving':'truck'
    }, function (res, error) {
      console.log(res); console.log(error)
      wx.hideLoading();
      if (res.data.success) {
        var strategyData = res.data.data;
        for (var i = 0; i < strategyData.length;i++){
          if (strategyData[i].strategy == that.data.strategy){
            strategyData[i].checked = true
          }else{
            strategyData[i].checked = false
          }
        }
        that.setData({
          strategyData: strategyData
        })
      } else {
        that.setData({
          hasData: false
        })
      }
    });
  },
  changeStrategy:function(e){
     this.setData({
       strategy: e.currentTarget.dataset.strategy
     })
    this.getDrivingRoute();
  },
  switchChange(e) {
    var that = this;
    var item = String(e.currentTarget.id), item_value = {};
    item_value[item] = e.detail.value;
    this.setData(item_value);
    that.getData();
  },
  initMap: function () {
    var that = this;
    var markers = [], lalt = [];

    amap = new amapFile.AMapWX({ key: 'a404e7cb1dcd34bb623e46fc3e46691e' });
    //运单导航坐标
    var wh_coord = String(that.data.wh_coord).split(',');
    markers.push({
      id: markers.length,
      title: that.data.name,
      callout: {
        content: that.data.name,
        fontSize: 11,
        color: '#ffffff',
        borderRadius: 2,
        bgColor: '#d81e06',
        padding: 3,
        display: 'ALWAYS'
      },
      iconPath: '/images/space.png',
      width: 0,
      height: 0,
      latitude: wh_coord[0],
      longitude: wh_coord[1]
    });
    markers.push({
      id: markers.length,
      title: "华聚盛（上海）企业管理有限公司",
      callout: {
        content: "华聚盛（上海）企业管理有限公司",
        fontSize: 11,
        color: '#ffffff',
        borderRadius: 2,
        bgColor: '#0081ff',
        padding: 3,
        display: 'ALWAYS'
      },
      iconPath: '/images/space.png',
      width: 0,
      height: 0,
      latitude: 22.574964,
      longitude: 113.849430
    });
    //设置表示点和地图上配件
    that.setData({
      markers: markers
    });
    that.getDrivingRoute();
  },
  setCurrentLocation: function (x, y) {
    var that = this;
    that.setData({
      // delivery_mile: ((Number(delivery_mile) || 0) / 1000).toFixed(1),
      // delivery_time: (Number(delivery_time) || 0).toFixed(2),
      // speed: speed,
      longitude: y,
      latitude: x
    });
    //console.log(that.data.markers)
    mapCtx.translateMarker({
      markerId: 888,
      autoRotate: true,
      duration: 1,
      destination: {
        latitude: x,
        longitude: y
      }
    });
  },
  getDrivingRoute: function () {
    var that = this;
    var markers = that.data.markers, pathData = [];
    for (var i = 0; i < markers.length; i++) {
      if (markers[i].id != 888) {
        pathData.push(markers[i]);
      }
    }
    var lalt = [];

    var firstPOI, lastPOI, waypoints = new Array(), w_index = 0;
    for (var i = 0; i < pathData.length; i++) {
      if (i == 0) {
        firstPOI = pathData[i].longitude + ',' + pathData[i].latitude;
      } else if (i == pathData.length - 1) {
        lastPOI = pathData[i].longitude + ',' + pathData[i].latitude;
      } else if (i < pathData.length - 1) {
        waypoints[w_index] = pathData[i].longitude + ',' + pathData[i].latitude;
        w_index++;
      }
      if (pathData[i].id != 888) {
        lalt.push({
          latitude: pathData[i].latitude,
          longitude: pathData[i].longitude
        });
      }

    }
    that.setData({
      lalt: lalt
    });
    try {
      amap.getDrivingRoute({
        origin: firstPOI,
        destination: lastPOI,
        waypoints: waypoints.join(";"),
        strategy: that.data.strategy,
        success: function (data) {
          console.log(data)
          var points = [];
          if (data.paths && data.paths[0] && data.paths[0].steps) {
            var steps = data.paths[0].steps;
            for (var i = 0; i < steps.length; i++) {
              var poLen = steps[i].polyline.split(';');
              for (var j = 0; j < poLen.length; j++) {
                points.push({
                  longitude: parseFloat(poLen[j].split(',')[0]),
                  latitude: parseFloat(poLen[j].split(',')[1])
                })
              }
            }
          }
          that.setData({
            polyline: [{
              points: points,
              color: "#0091ff",
              width: 3
            }]
          });
          if (data.paths[0] && data.paths[0].distance) {
            var duration = Number(data.paths[0].duration) + pathData.length * 30 * 60;
            var hourToTime = util.hourToTime(duration);
            that.setData({
              distance: (data.paths[0].distance / 1000).toFixed(1),
              duration: Number(duration).toFixed(2),
              duration_hour: hourToTime.hour,
              duration_minute: hourToTime.minute,
              restriction: data.paths[0].restriction,
              strategyText: data.paths[0].strategy,
              tolls: data.paths[0].tolls
            });
          }
          mapCtx.includePoints({
            padding: [10],
            points: lalt
          })
        },
        fail: function (err) {
          console.log(err)
        }
      })
    } catch (e) { }

  },
  saveStrategy: function () {
    var that = this;
    if(that.data.id == '' || that.data.id == undefined){
      wx.setStorage({
        key: "strategy",
        data: {
          routing_type: that.data.vehicleType ? 'driving' : 'truck',
          strategy: that.data.strategy
        },
        success: function () {
          wx.navigateBack({
            delta: 1
          })
        }
      });
      return false;
    }
    wx.showLoading({
      title: '保持策略中...'
    });
    util.postData("/xypapi/map/routerCalculate/saveStrategy", {
      id: that.data.id,
      routing_type: that.data.vehicleType ?'driving':'truck',
      strategy: that.data.strategy
    }, function (res, error) {
      console.log(res); console.log(error)
      if (res.data.success) {
        wx.showToast({
          title: res.data.data,
          icon: 'success',
          duration: 2000,
          mask: true,
          success: function () {
            
          }
        })
      } else {
        wx.showToast({
          title: res.data.data,
          image: '/images/wrong.png',
          duration: 2000
        })
      }
      wx.hideLoading();
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    mapCtx = wx.createMapContext('map');
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})